<!--
* @description 消息提醒设置
* @author zywu
* @date 2021/04/23 10:12:49
!-->
<template>
  <div>
    <div style="padding:10px;font-size:18px;">基本信息</div>
    <el-form
      ref="editForm"
      :model="editForm"
      :rules="editFormRules"
      label-width="100px"
      :disabled="readonly"
      @submit.native.prevent
    >
      <el-row>
        <el-col :span="12">
          <el-form-item v-if="isMuilUnitUser" label="联网单位" prop="orgId">
            <el-select filterable @change="onOrgChange" v-model="editForm.orgId" placeholder="请选择联网单位">
              <el-option
                v-for="item in orgOptions"
                :key="item.organizationId"
                :label="item.shortName"
                :value="item.organizationId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="建筑物" prop="unitFloor">
            <el-input v-if="readonly" v-model="editForm.unitFloorName" type="text"></el-input>
            <tree-select
              v-else
              class="tree-select--block"
              v-model="editForm.unitFloor"
              filterable
              :data="buildList"
              :defaultProps="buildDefaultProps"
              :checkedKeys="defaultCheckedFbsId"
              clearable
              @node-click="handleNodeClick"
              :nodeKey="buildNodeKey"
            ></tree-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="10">
          <el-form-item label="屏蔽设备监测状态" label-width="155px" prop="monitorStatus">
            <el-checkbox-group v-model="editForm.monitorStatus">
              <el-checkbox label="10">报警</el-checkbox>
              <el-checkbox label="20">故障</el-checkbox>
              <el-checkbox label="40">联动</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-col>
        <el-col :span="11" style="margin-top:10px;">
          <span style="color:#E6A23C;">未选择的系统将不进行屏蔽</span>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="屏蔽时间" prop="time">
            <el-date-picker
              v-model="editForm.time"
              type="datetimerange"
              align="right"
              unlink-panels
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="yyyy-MM-dd HH:mm"
              value-format="yyyy-MM-dd HH:mm"
              :default-time="['00:00:00','23:59:59']"
              style="width:100%;"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="屏蔽原因" prop="monitorContent">
            <el-input type="textarea" v-model.trim="editForm.monitorContent"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="d-flex ai-center jc-between" style="padding:0 0 10px 10px;">
      <span style="font-size:18px;">屏蔽设备</span>
      <el-button v-if="!readonly" type="primary" plain icon="el-icon-plus" @click="openDeviceDialog">添加屏蔽设备</el-button>
    </div>
    <el-table
      v-loading="loading"
      :data="pageData"
      ref="mainTable"
      style="width: 100%;border: 1px solid #EBEEF5;border-bottom: none;"
    >
      <el-table-column label="序号" type="index" width="50" align="center"></el-table-column>
      <el-table-column prop="structureName" label="名称"></el-table-column>
      <el-table-column prop="fcFacilitiesName" label="设备类型" width="200"></el-table-column>
      <el-table-column prop="levelLocation" label="位置"></el-table-column>
      <el-table-column label="操作" width="80" align="center">
        <template slot-scope="scope">
          <el-button v-if="!readonly" @click="handleDel(scope.$index, scope.row)" type="text" size="small">移除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      @size-change="sizeChange"
      @current-change="pageChange"
      :current-page="pageIndex"
      :page-sizes="[2,10, 50, 100]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="tableData.length"
      style="text-align:right;"
    ></el-pagination>
    <el-dialog
      :close-on-click-modal="false"
      title="添加屏蔽设备"
      width="1150px"
      top="10vh"
      v-if="deviceDialogShow"
      :visible.sync="deviceDialogVisible"
      @close="closeDeviceDialog"
      v-dialogDrag
      append-to-body
    >
      <add-device
        ref="ChooseDevice"
        :visible="deviceDialogVisible"
        :orgId="editForm.orgId"
        :buildId="editForm.unitFloor"
        :defaultSelected="tableData"
      ></add-device>
      <div slot="footer" class="dialog-footer" style="padding-top:20px;text-align:center;">
        <el-button type="primary" @click="handleAddDevice">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addMsgAlert, getMsgAlertDetail } from '@/api/sysConfig'
import TreeSelect from '@/libs/TreeSelect/Main'
import { getFbsTree } from '@/api/fbs'
import util from '@/utils/util'
import { mapState, mapGetters } from 'vuex'
import AddDevice from './PushConfigChoose'

export default {
  name: 'AssetClassLibForm',
  components: { TreeSelect, AddDevice },
  props: {
    editInfo: {
      type: Object,
      required: false,
    },
    closeDialog: {
      type: Function,
      required: true,
    },
    readonly: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      qiniuData: {
        //上传图片携带的参数
        token: '',
        key: '',
        fileList: [],
      },
      roleOptions: [],
      unRelateVideoTotal: 0,
      editForm: {
        id: '',
        orgId: '',
        unitFloor: '',
        monitorContent: '',
        monitorStatus: ['10'],
        time: [],
      },
      editFormRules: {
        orgId: [{ required: true, message: '请选择', trigger: 'change' }],
        time: [{ required: true, message: '请选择', trigger: 'change' }],
        monitorContent: [
          { required: true, message: '请填写', trigger: 'blur' },
        ],
      },
      // 建筑物
      buildDefaultProps: {
        children: 'nodes',
        label: 'text',
        value: 'id',
      },
      buildNodeKey: 'id',
      defaultCheckedFbsId: [],
      buildList: [],
      loading: false,
      tableData: [],
      pageIndex: 1,
      total: 0,
      pageSize: 10,
      deviceDialogVisible: false,
      deviceDialogShow: false,
    }
  },
  computed: {
    ...mapState(['orgOptions', 'userinfo']),
    ...mapGetters(['isMuilUnitUser']),
    pageData() {
      return this.tableData.slice(
        this.pageSize * (this.pageIndex - 1),
        this.pageSize * this.pageIndex
      )
    },
    isEdit() {
      return !!this.editForm.id
    },
  },
  watch: {},
  created() {
    let infoObj = this.editInfo
    if (infoObj.id) {
      //编辑
      this.editForm.id = infoObj.id
      this.getDetail()
    }
  },
  methods: {
    getDetail() {
      getMsgAlertDetail({ id: this.editForm.id }).then((res) => {
        this.tableData = res.data.monitorStructures
        this.editForm = {
          ...res.data,
          monitorStructures: undefined,
          time: [
            res.data.monitorStartTime.substr(0, 16),
            res.data.monitorEndTime.substr(0, 16),
          ],
          monitorStatus: res.data.monitorStatus
            ? res.data.monitorStatus.split(',')
            : [],
          unitFloorName: this.editInfo.unitFloorName,
        }
        this.getBuildTree()
      })
    },
    clearTableData(type) {
      if (this.tableData.length > 0) {
        this.$alert(
          '修改' +
            (type == 1 ? '联网单位' : '建筑物') +
            '，已添加的屏蔽设备将清空',
          '提示',
          {
            confirmButtonText: '确定',
            callback: (action) => {
              this.tableData = []
            },
          }
        )
      }
    },
    onOrgChange() {
      this.editForm.unitFloor = ''
      this.getBuildTree()
      this.clearTableData(1)
    },
    getBuildTree() {
      getFbsTree({
        organizationId: this.editForm.orgId,
      }).then((res) => {
        this.buildList = res.data.length === 0 ? [] : res.data
        this.$nextTick(() => {
          this.defaultCheckedFbsId = this.editForm.unitFloor
            ? this.editForm.unitFloor.toString().split(',')
            : []
        })
      })
    },
    handleAddDevice() {
      // if (this.$refs.ChooseDevice.selectedList.length == 0) {
      //   return this.$message.error('请选择屏蔽设备')
      // }
      this.tableData = JSON.parse(
        JSON.stringify(this.$refs.ChooseDevice.selectedList)
      )
      this.closeDeviceDialog()
    },
    sizeChange(val) {
      this.pageSize = val
    },
    pageChange(val) {
      this.pageIndex = val
    },
    handleDel(index, row) {
      this.tableData.splice((this.pageIndex - 1) * this.pageSize + index, 1)
      // if (!this.editForm.id) {

      // }
      // this.$confirm('删除后将不可恢复，确认要删除吗？', '消息提醒设置删除', {
      //   confirmButtonText: '删除',
      //   cancelButtonText: '取消',
      //   type: 'warning',
      //   roundButton: true,
      // })
      //   .then(() => {
      //     this.requestDel()
      //   })
      //   .catch(() => {})
    },
    requestDel(index, item) {
      // Dao.delAc({ id: row.id }).then((res) => {
      //   if (res.status === 200) {
      //     this.$message({
      //       type: 'success',
      //       message: '删除成功!',
      //     })
      //     this.getList(1)
      //   } else {
      //     this.$message.error(res.info)
      //   }
      // })
      this.tableData.splice((this.pageIndex - 1) * this.pageSize + index, 1)
    },
    openDeviceDialog() {
      if (!this.editForm.orgId) {
        return this.$message.error('请先选择联网单位')
      }
      this.deviceDialogShow = true
      this.deviceDialogVisible = true
    },
    closeDeviceDialog() {
      this.deviceDialogVisible = false
    },
    handleNodeClick(data) {
      if (data.id != this.editForm.unitFloor) {
        this.clearTableData(2)
      }
    },
    saveEdit() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          let {
            id,
            orgId,
            unitFloor,
            time,
            monitorStatus,
            monitorContent,
            createUserAccount,
          } = this.editForm
          let param = {
            orgId,
            monitorStartTime: time[0],
            monitorEndTime: time[1],
            monitorStatus: monitorStatus.join(','),
            monitorContent,
            monitorStructureIds: this.tableData
              .map((n) => {
                return n.structureId
              })
              .join(','),
          }
          if (id) {
            param.id = id
            param.updateUserAccount = this.userinfo.accountName
            param.createUserAccount = createUserAccount
          } else {
            param.createUserAccount = this.userinfo.accountName
          }
          if (unitFloor) param.unitFloor = unitFloor
          addMsgAlert(param).then((res) => {
            if (res.status === 200) {
              this.$message({
                type: 'success',
                message: '保存成功！!',
              })
              this.closeDialog(true)
            } else {
              this.$message.error(res.info)
            }
          })
        } else {
          return false
        }
      })
    },
  },
}
</script>
